package cn.tjnext.apply.service;

import cn.tjnext.apply.dao.UserDao;
import cn.tjnext.apply.entity.UserEntity;
import cn.tjnext.apply.repositories.UserRepository;
import cn.tjnext.apply.utils.EncryptHelper;
import cn.tjnext.apply.web.model.CheckLoginModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by cp on 2017/7/31.
 */
@Service
@Transactional(readOnly = true)
public class UserService extends AbstractService<UserEntity, UserRepository, UserDao> {

    @Autowired
    private UserDao userDao;

    @Override
    protected UserDao getDao() {
        return userDao;
    }

    /**
     * 验证手机号是否已被注册
     * @param data
     * @return
     */
    public boolean checkLoginPhone(String data) {
        return userDao.findByPhone(data) == null;
    }

    /**
     * 验证登录密码
     * @param phone
     * @param password
     * @return
     */
    public CheckLoginModel checkPassword(String phone, String password) {
        CheckLoginModel checkLoginModel = new CheckLoginModel();
        UserEntity userEntity = userDao.findByPhone(phone);
        if (userEntity !=null) {
            checkLoginModel.setUserId(userEntity.getPkId());
            String md5Password = null;
            try {
                md5Password = EncryptHelper.encodeMD5(password);
            } catch (Exception e) {
                return new CheckLoginModel(e.getMessage());
            }
            if (!userEntity.getPassword().equals(md5Password)) {
                return new CheckLoginModel("密码错误");
            };
        } else {
            checkLoginModel.setErrorMessage("用户不存在");
        }
        return checkLoginModel;
    }
}
